<template>
  <el-form ref="classForm" :model="form" label-width="20px" style="margin-top: 20px">
    <el-form-item class="form-item">
      <el-select v-model="seriesID" placeholder="选择系列" value="" @change="chapterList">
        <el-option
          v-for="item in series"
          :key="item.id"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-button type="primary" style="margin-left: 5px" @click="add">添加章节</el-button>
    </el-form-item>
    <el-row>
      <div v-for="item in chapters" :key="item.id" class="card">
        <chapter-card
          :item="item"
          :list="chapters"
          :total="total"
          :series="seriesID"
          @edit="edit"
          @reload="chapterList(seriesID)"
        />
      </div>
    </el-row>
    <el-dialog :visible.sync="dialog" :title="title">
      <chapter-dialog
        :form="form"
        :total="total"
        :series="seriesID"
        :mode="isEditMode"
        @close="dialog = false"
        @reload="chapterList(seriesID)"
      />
    </el-dialog>
  </el-form>
</template>

<script>
import { fetchChapterList } from '../../api/chapter'
import { fetchSeriesList } from '../../api/serires'
import ChapterCard from './module/ChapterCard'
import ChapterDialog from './module/ChapterDialog'
export default {
  name: 'Chapter',
  components: { ChapterDialog, ChapterCard },
  data() {
    return {
      chapters: [],
      series: [],
      total: null,
      title: '',
      dialog: false,
      isEditMode: false,
      seriesID: null,
      form: {
        id: null,
        name: '',
        page_url: '',
        map_url: '',
        points: ''
      }
    }
  },
  created() {
    this.seriesList()
  },
  methods: {
    /**
     * resetForm 重置表单数据
     * */
    resetForm() {
      this.form = this.$options.data().form
    },
    seriesList() {
      fetchSeriesList().then(response => {
        if (response.data.total !== 0) {
          this.series = response.data.items
          this.seriesID = response.data.items[0].id
          this.chapterList(this.seriesID)
        } else {
          this.$WARNING('还未创建系列')
        }
      }).catch(() => {
        this.$ERROR('获取系列失败')
      })
    },
    chapterList(id) {
      const config = { series: id }
      fetchChapterList(config).then(response => {
        if (response.data.total !== 0) {
          this.chapters = response.data.items
          this.total = response.data.total
          this.$sort(this.chapters)
        } else {
          this.chapters = []
          this.total = 0
          this.$WARNING('该系列还未创建章节')
        }
      }).catch(() => {
        this.$ERROR('获取章节失败')
      })
    },
    add() {
      this.resetForm()
      this.$setDialog(true, '创建章节', false)
    },
    edit(item) {
      this.$setDialog(true, '更新章节', true)
      this.form = item
    }
  }
}
</script>

<style scoped>
    .card{
        width:330px;
        display:inline-block;
        margin-left: 20px;
    }
</style>
